<template>
  <div class="auth-container">
    <!-- 关闭按钮 -->
    <button class="close-btn" @click="handleClose">×</button>

    <!-- 登录/注册切换 -->
    <div class="toggle-buttons">
      <button
          :class="{ active: isLogin }"
          @click="toggleMode('login')"
      >
        登录
      </button>
      <button
          :class="{ active: !isLogin }"
          @click="toggleMode('register')"
      >
        注册
      </button>
    </div>

    <!-- 登录表单 -->
    <div v-if="isLogin" class="form-container">
      <h2>欢迎回来！</h2>
      <div class="form-group">
        账号
        <input
            v-model="loginForm.phoneNumber"
            type="text"
            placeholder="请输入手机号"
        />
      </div>
      <div v-if="loginType === 'password'" class="form-group">
        密码
        <input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
        />
      </div>
      <div v-else class="form-group">
        验证码
        <input
            class="registerCode"
            v-model="loginForm.code"
            type="text"
            placeholder="请输入验证码"
        />
        <button class="code-btn" @click="sendCode">
          {{ codeSent ? `${countdown}秒后重发` : '获取验证码' }}
        </button>
      </div>
      <div class="form-group">
        <button class="submit-btn" @click="handleLogin">
          {{ loginType === 'password' ? '登录' : '验证码登录' }}
        </button>
      </div>
      <div class="switch-login-type">
        <span @click="switchLoginType">
          {{ loginType === 'password' ? '使用验证码登录' : '使用密码登录' }}
        </span>
      </div>
    </div>

    <!-- 注册表单 -->
    <div v-else class="form-container">
      <h2>注册新账号</h2>
      <div class="form-group">
        手机号
        <input
            v-model="registerForm.phoneNumber"
            type="text"
            placeholder="请输入手机号"
        />
      </div>
      <div class="form-group">
        验证码
        <input
            v-model="registerForm.code"
            class="registerCode"
            type="text"
            placeholder="请输入验证码"
        />
        <button class="code-btn" @click="sendCode">
          {{ codeSent ? `${countdown}秒后重发` : '获取验证码' }}
        </button>
      </div>
<!--      <div class="form-group">-->
<!--        <input-->
<!--            v-model="registerForm.password"-->
<!--            type="password"-->
<!--            placeholder="请设置密码"-->
<!--        />-->
<!--      </div>-->
      <div class="form-group">
        <button class="submit-btn" @click="handleRegister">注册</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue';

// 登录/注册状态
const isLogin = ref(true);

// 登录方式：password 或 code
const loginType = ref('password');

// 登录表单数据
const loginForm = reactive({
  phoneNumber: '13211664090',
  password: '12366',
  code: ''
});

// 注册表单数据
const registerForm = reactive({
  phoneNumber: '',
  code: '',
});

// 验证码状态
const codeSent = ref(false);
const countdown = ref(60);

// 切换登录/注册模式
const toggleMode = (mode) => {
  isLogin.value = mode === 'login';
};

// 切换登录方式（密码/验证码）
const switchLoginType = () => {
  loginType.value = loginType.value === 'password' ? 'code' : 'password';
};

// 发送验证码
const sendCode = async () => {
  if (codeSent.value) return;
  codeSent.value = true;
  startCountdown();
  // 这里调用后端发送验证码的接口
  console.log('发送验证码至:', isLogin.value ? loginForm.phoneNumber : registerForm.phoneNumber);
  let res = null;
  if(isLogin.value){
    res = await getCode(loginForm.phoneNumber)
  }else{
    res = await getCode(registerForm.phoneNumber)
  }
  console.log(res)
  if(res.code !== 200){
    ElNotification.error(res.message)
  }else {
    ElNotification.success("验证码为："+res.data)
  }
};

// 开始倒计时
const startCountdown = () => {
  const timer = setInterval(() => {
    if (countdown.value === 0) {
      clearInterval(timer);
      codeSent.value = false;
      countdown.value = 60;
    } else {
      countdown.value--;
    }
  }, 1000);
};
import {login,register,getCode,loginByCode} from '@/api/api.js'
import {useUserStore} from "@/stores/userInfoStore.js";
import emitter from "@/utils/emitter.js";
import {useLoginStore} from "@/stores/LoginStore.js";
const userStore = useUserStore()
const loginStore = useLoginStore()
import { ElNotification } from 'element-plus'
// 处理登录
const handleLogin = async () => {
  if (loginType.value === 'password') {
    console.log('密码登录:', loginForm);
    // 调用后端密码登录接口
    const res = await login(loginForm)
    console.log(res)
    if(res.code === 200){
      userStore.setUserInfo(res.data)
      localStorage.setItem("token",res.data.token)
      localStorage.setItem("userId",res.data.userId)
      loginStore.setPromptLogin(false)
      emit('close',false)
      emitter.emit('userInfo',res.data)
    }else{
      ElNotification({
        title: '错误',
        message: res.message,
        type: 'error',
      })
    }
  } else {
    console.log('验证码登录:', loginForm);
    // 调用后端验证码登录接口
    const res = await loginByCode(loginForm)
    console.log(res)
    handleEnd(res)
  }
};

// 处理注册
const handleRegister = async () => {
  console.log('注册:', registerForm);
  // 调用后端注册接口
  const res = await register(registerForm)
  console.log(res)
  handleEnd(res)
};

const handleEnd = (res) => {
  if(res.code === 200){
    userStore.setUserInfo(res.data)
    localStorage.setItem("token",res.data.token)
    localStorage.setItem("userId",res.data.userId)
    loginStore.setPromptLogin(false)
    emit('close',false)
    emitter.emit('userInfo',res.data)
  }else{
    ElNotification({
      title: '错误',
      message: res.message,
      type: 'error',
    })
  }
  console.log('登录/注册弹窗关闭');
};
// 关闭按钮事件
const handleClose = () => {
  console.log('关闭登录/注册弹窗');
  // 触发父组件事件
  emit('close',false);
};

// 定义 emit
const emit = defineEmits(['close']);
</script>

<style scoped>
.form-group .registerCode{
  width: 63%;
}
.auth-container {
  position: relative;
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  top: 100px;

}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: none;
  border: none;
  font-size: 24px;
  color: #ff4d6d;
  cursor: pointer;
}

.close-btn:hover {
  color: #ff758f;
}

.toggle-buttons {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.toggle-buttons button {
  padding: 10px 20px;
  border: none;
  border-radius: 20px;
  background-color: white;
  color: gray;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.toggle-buttons button.active {
  background-color: var(--el-color-primary);
  color: #fff;
}

.form-container {
  text-align: center;
}

.form-container h2 {
  color: var(--el-color-primary);
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.form-group input {
  width: 85%;
  padding: 10px;
  border: 1px solid gray;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.form-group input:focus {
  border-color: var(--el-color-primary);
}

.code-btn {
  margin-left: 10px;
  padding: 5px 10px;
  border: none;
  border-radius: 15px;
  background-color: #ffccd5;
  color: #ff4d6d;
  font-size: 12px;
  cursor: pointer;
}

.submit-btn {
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 20px;
  background-color: var(--el-color-primary);
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: deepskyblue;
}

.switch-login-type {
  margin-top: 10px;
  color: #ff4d6d;
  font-size: 14px;
  cursor: pointer;
}

.switch-login-type:hover {
  text-decoration: underline;
}
</style>